<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>司法取证 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
        }
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        .btn {
            transition: all 0.3s ease;
        }
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
        }
        .input-field {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        .input-field:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        .table-row {
            transition: all 0.2s ease;
        }
        .table-row:hover {
            background-color: rgba(59, 130, 246, 0.05);
        }
        .back-btn {
            transition: all 0.3s ease;
        }
        .back-btn:hover {
            background-color: rgba(59, 130, 246, 0.1);
        }
        .tab-btn {
            transition: all 0.3s ease;
            border-bottom: 2px solid transparent;
        }
        .tab-btn.active {
            border-bottom-color: #3b82f6;
            color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.05);
        }
        .personnel-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .personnel-card:hover {
            transform: translateY(-2px);
        }
        .personnel-card.selected {
            border-color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.05);
        }
        /* 新增状态徽章样式 */
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 2px 8px;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        .status-success {
            background-color: rgba(16, 185, 129, 0.1);
            color: rgb(5, 150, 105);
        }
        .status-failed {
            background-color: rgba(239, 68, 68, 0.1);
            color: rgb(220, 38, 38);
        }
        .status-active {
            background-color: rgba(16, 185, 129, 0.1);
            color: rgb(5, 150, 105);
        }
        .status-inactive {
            background-color: rgba(156, 163, 175, 0.1);
            color: rgb(107, 114, 128);
        }
        /* 加载状态 */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        .loading::after {
            content: '';
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-left: 8px;
            border: 2px solid rgba(59, 130, 246, 0.3);
            border-top-color: #3b82f6;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        /* 空数据提示 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #64748b;
        }
        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            color: #cbd5e1;
        }
        /* Toast 通知样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        .toast {
            padding: 12px 20px;
            margin-bottom: 10px;
            border-radius: 8px;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.3s ease-out;
        }
        .toast.success {
            background-color: #10b981;
        }
        .toast.error {
            background-color: #ef4444;
        }
        .toast.info {
            background-color: #3b82f6;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        /* 表单验证错误 */
        .input-error {
            border-color: #ef4444;
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
        .error-message {
            color: #ef4444;
            font-size: 0.75rem;
            margin-top: 4px;
        }
    </style>
</head>
<body class="p-6">
    <div class="container mx-auto">
        <!-- Toast 通知容器 -->
        <div id="toastContainer" class="toast-container"></div>
        
        <!-- 页面标题和返回按钮 -->
        <div class="mb-6 flex items-center justify-between">
            <h1 class="text-3xl font-bold text-gray-800">司法取证</h1>
            <a href="index.html" class="back-btn px-4 py-2 rounded-lg flex items-center gap-2 text-gray-600 transition-all duration-300 hover:bg-blue-50">
                <i class="fas fa-arrow-left"></i>
                <span>返回首页</span>
            </a>
        </div>

        <!-- 标签页导航 -->
        <div class="card mb-6">
            <div class="flex border-b border-gray-200">
                <button class="tab-btn px-6 py-4 font-medium active" onclick="switchTab('personnel')">取证人员</button>
                <button class="tab-btn px-6 py-4 font-medium" onclick="switchTab('mofn')">MOFN验证</button>
                <button class="tab-btn px-6 py-4 font-medium" onclick="switchTab('logs')">取证日志</button>
            </div>
        </div>

        <!-- 取证人员标签页 -->
        <div id="personnelTab" class="tab-content">
            <div class="card p-6 mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold">取证人员管理</h2>
                    <button class="btn btn-primary px-4 py-2 rounded-lg" onclick="openAddPersonnelModal()">
                        <i class="fas fa-plus"></i> 新增人员
                    </button>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="personnelGrid">
                    <!-- 人员卡片将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>

        <!-- MOFN验证标签页 -->
        <div id="mofnTab" class="tab-content hidden">
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">MOFN验证</h2>
                <div class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">选择需要验证的密钥</label>
                            <select class="input-field w-full px-4 py-2" id="keyToVerify">
                                <!-- 密钥选项将通过JavaScript动态生成 -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">需要的验证人数 (M/N)</label>
                            <div class="flex items-center gap-2">
                                <input type="number" class="input-field w-16 px-4 py-2" id="requiredM" min="1" value="2">
                                <span class="text-gray-500">/</span>
                                <input type="number" class="input-field w-16 px-4 py-2" id="totalN" min="1" value="3" disabled>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择参与验证的人员</label>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4" id="verifiersGrid">
                            <!-- 验证人员将通过JavaScript动态生成 -->
                        </div>
                    </div>

                    <div class="flex justify-center">
                        <button class="btn btn-primary px-8 py-3 rounded-lg" onclick="startMofnVerification()">
                            <i class="fas fa-lock"></i> 开始验证
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 取证日志标签页 -->
        <div id="logsTab" class="tab-content hidden">
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">取证日志</h2>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b border-gray-200">
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">日志ID</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作时间</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作类型</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作人员</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥ID</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">结果</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">详情</th>
                            </tr>
                        </thead>
                        <tbody id="forensicsLogsTableBody">
                            <!-- 取证日志将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增人员模态框 -->
    <div id="addPersonnelModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">新增取证人员</h3>
                <button onclick="closeAddPersonnelModal()" class="text-gray-500 hover:text-gray-700 transition-colors duration-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="addPersonnelForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                    <input type="text" name="name" class="input-field w-full px-4 py-2" placeholder="请输入姓名" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">身份证号</label>
                    <input type="text" name="idCard" class="input-field w-full px-4 py-2" placeholder="请输入18位身份证号" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">单位</label>
                    <input type="text" name="organization" class="input-field w-full px-4 py-2" placeholder="请输入所属单位" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">职务</label>
                    <input type="text" name="position" class="input-field w-full px-4 py-2" placeholder="请输入职务" required>
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeAddPersonnelModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors duration-200">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg hover:bg-blue-100 transition-colors duration-200">添加人员</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑人员模态框 -->
    <div id="editPersonnelModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">编辑取证人员</h3>
                <button onclick="closeEditPersonnelModal()" class="text-gray-500 hover:text-gray-700 transition-colors duration-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="editPersonnelForm" class="space-y-4">
                <input type="hidden" name="id">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                    <input type="text" name="name" class="input-field w-full px-4 py-2" placeholder="请输入姓名" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">身份证号</label>
                    <input type="text" name="idCard" class="input-field w-full px-4 py-2" placeholder="请输入18位身份证号" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">单位</label>
                    <input type="text" name="organization" class="input-field w-full px-4 py-2" placeholder="请输入所属单位" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">职务</label>
                    <input type="text" name="position" class="input-field w-full px-4 py-2" placeholder="请输入职务" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                    <select name="status" class="input-field w-full px-4 py-2">
                        <option value="active">可用</option>
                        <option value="inactive">不可用</option>
                    </select>
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeEditPersonnelModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors duration-200">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg hover:bg-blue-100 transition-colors duration-200">保存修改</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../common/common.js"></script>
    <script>
        // 初始化数据
        function initData() {
            // 显示加载状态
            const personnelGrid = document.getElementById('personnelGrid');
            personnelGrid.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">加载中...</div>';
            
            // 初始化取证人员数据
            if (!localStorage.getItem('forensicsPersonnel')) {
                const initialPersonnel = [
                    { id: 'FP-001', name: '管理员', idCard: '110101199001011234', organization: '公安局', position: '法医', status: 'active' },
                    { id: 'FP-002', name: '管理员', idCard: '110101199102022345', organization: '检察院', position: '检察官', status: 'active' },
                    { id: 'FP-003', name: '管理员', idCard: '110101199203033456', organization: '法院', position: '法官', status: 'active' },
                    { id: 'FP-004', name: '管理员', idCard: '110101199304044567', organization: '公安局', position: '刑警', status: 'active' },
                    { id: 'FP-005', name: '管理员', idCard: '110101199405055678', organization: '司法局', position: '法律顾问', status: 'active' }
                ];
                localStorage.setItem('forensicsPersonnel', JSON.stringify(initialPersonnel));
            }

            // 初始化取证日志数据
            if (!localStorage.getItem('forensicsLogs')) {
                const initialLogs = [
                    { id: 'LOG-001', time: '2024-01-15 14:30', type: 'MOFN验证', operator: '张三,李四', keyId: 'KMS-001', result: 'success', details: '成功完成密钥KMS-001的2/3验证' },
                    { id: 'LOG-002', time: '2024-01-14 10:20', type: '密钥导出', operator: '王五', keyId: 'KMS-002', result: 'success', details: '成功导出密钥KMS-002用于司法取证' },
                    { id: 'LOG-003', time: '2024-01-13 16:45', type: 'MOFN验证', operator: '张三,李四,王五', keyId: 'KMS-003', result: 'failed', details: '验证失败，人员权限不足' },
                    { id: 'LOG-004', time: '2024-01-12 09:15', type: '人员添加', operator: '系统管理员', keyId: '-', result: 'success', details: '添加了新的取证人员孙七' },
                    { id: 'LOG-005', time: '2024-01-11 15:30', type: 'MOFN验证', operator: '李四,王五,赵六', keyId: 'KMS-004', result: 'success', details: '成功完成密钥KMS-004的3/3验证' }
                ];
                localStorage.setItem('forensicsLogs', JSON.stringify(initialLogs));
            }
        }

        // 加载取证人员
        function loadForensicsPersonnel() {
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const grid = document.getElementById('personnelGrid');
            grid.innerHTML = '';

            if (personnel.length === 0) {
                grid.innerHTML = `
                    <div class="col-span-full empty-state">
                        <i class="fas fa-users"></i>
                        <h3 class="text-lg font-medium mb-2">暂无取证人员</h3>
                        <p class="text-sm">点击"新增人员"按钮添加取证人员</p>
                    </div>
                `;
                return;
            }

            personnel.forEach(function(person, index) {
                const card = document.createElement('div');
                card.className = 'personnel-card card p-4 fade-in';
                card.style.animationDelay = `${index * 0.05}s`;
                card.innerHTML = `
                    <div class="flex justify-between items-start mb-2">
                        <h3 class="font-semibold">${person.name}</h3>
                        <span class="status-badge ${person.status === 'active' ? 'status-active' : 'status-inactive'}">
                            ${person.status === 'active' ? '可用' : '不可用'}
                        </span>
                    </div>
                    <div class="space-y-1 text-sm text-gray-600">
                        <div><span class="text-gray-500">身份证号:</span> ${person.idCard}</div>
                        <div><span class="text-gray-500">单位:</span> ${person.organization}</div>
                        <div><span class="text-gray-500">职务:</span> ${person.position}</div>
                    </div>
                    <div class="flex gap-2 mt-4">
                        <button onclick="editPersonnel('${person.id}')" class="btn btn-primary px-2 py-1 text-sm rounded hover:bg-blue-100 transition-colors duration-200">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="togglePersonnelStatus('${person.id}')" class="btn btn-primary px-2 py-1 text-sm rounded hover:bg-blue-100 transition-colors duration-200">
                            <i class="fas ${person.status === 'active' ? 'fa-lock' : 'fa-unlock'}"></i>
                        </button>
                    </div>
                `;
                grid.appendChild(card);
            });
        }

        // 加载可验证的密钥
        function loadKeysForVerification() {
            const keys = JSON.parse(localStorage.getItem('keys')) || [];
            const select = document.getElementById('keyToVerify');
            select.innerHTML = '<option value="">选择密钥</option>';

            if (keys.length === 0) {
                select.innerHTML = '<option value="">暂无可用密钥</option>';
                return;
            }

            keys.forEach(function(key) {
                const option = document.createElement('option');
                option.value = key.id;
                option.textContent = `${key.id} - ${key.name} (${key.algorithm})`;
                select.appendChild(option);
            });
        }

        // 加载验证人员
        function loadVerifiers() {
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const grid = document.getElementById('verifiersGrid');
            grid.innerHTML = '';

            const activePersonnel = personnel.filter(function(p) { return p.status === 'active'; });
            
            if (activePersonnel.length === 0) {
                grid.innerHTML = `
                    <div class="col-span-full empty-state">
                        <i class="fas fa-user-check"></i>
                        <h3 class="text-lg font-medium mb-2">暂无可用验证人员</h3>
                        <p class="text-sm">请先在取证人员管理中添加可用人员</p>
                    </div>
                `;
                document.getElementById('totalN').value = 0;
                return;
            }

            activePersonnel.forEach(function(person, index) {
                const card = document.createElement('div');
                card.className = 'personnel-card card p-4 fade-in';
                card.style.animationDelay = `${index * 0.05}s`;
                card.onclick = function() { toggleVerifierSelection(person.id); };
                card.innerHTML = `
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="verifier-${person.id}" class="rounded text-blue-600 focus:ring-blue-500">
                        <label for="verifier-${person.id}" class="font-medium">${person.name}</label>
                    </div>
                    <div class="text-sm text-gray-600 mt-1">${person.organization} - ${person.position}</div>
                `;
                grid.appendChild(card);
            });

            // 更新总人数
            document.getElementById('totalN').value = activePersonnel.length;
        }

        // 加载取证日志
        function loadForensicsLogs() {
            const logs = JSON.parse(localStorage.getItem('forensicsLogs')) || [];
            const tbody = document.getElementById('forensicsLogsTableBody');
            tbody.innerHTML = '';

            if (logs.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="py-12 text-center text-gray-500">
                            <i class="fas fa-file-alt text-4xl mb-3"></i>
                            <div>暂无取证日志记录</div>
                        </td>
                    </tr>
                `;
                return;
            }

            logs.forEach(function(log, index) {
                const row = document.createElement('tr');
                row.className = 'table-row border-b border-gray-100 fade-in';
                row.style.animationDelay = `${index * 0.03}s`;
                let resultClass = 'status-success';
                let resultText = '成功';
                if (log.result === 'failed') {
                    resultClass = 'status-failed';
                    resultText = '失败';
                }
                row.innerHTML = `
                    <td class="py-3 px-4">${log.id}</td>
                    <td class="py-3 px-4">${log.time}</td>
                    <td class="py-3 px-4">${log.type}</td>
                    <td class="py-3 px-4">${log.operator}</td>
                    <td class="py-3 px-4">${log.keyId}</td>
                    <td class="py-3 px-4">
                        <span class="status-badge ${resultClass}">${resultText}</span>
                    </td>
                    <td class="py-3 px-4">${log.details}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(function(content) {
                content.classList.add('hidden');
            });

            // 移除所有标签按钮的激活状态
            document.querySelectorAll('.tab-btn').forEach(function(btn) {
                btn.classList.remove('active');
            });

            // 显示当前标签页内容
            document.getElementById(tabName + 'Tab').classList.remove('hidden');

            // 添加当前标签按钮的激活状态
            event.target.classList.add('active');

            // 加载对应标签页的数据
            if (tabName === 'mofn') {
                loadKeysForVerification();
                loadVerifiers();
            } else if (tabName === 'logs') {
                loadForensicsLogs();
            }
        }

        // 新增取证人员
        function openAddPersonnelModal() {
            document.getElementById('addPersonnelModal').classList.remove('hidden');
        }

        function closeAddPersonnelModal() {
            document.getElementById('addPersonnelModal').classList.add('hidden');
            document.getElementById('addPersonnelForm').reset();
        }

        // 表单提交事件
        document.getElementById('addPersonnelForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 表单验证
            const form = e.target;
            const name = form.name.value.trim();
            const idCard = form.idCard.value.trim();
            const organization = form.organization.value.trim();
            const position = form.position.value.trim();
            
            // 清除之前的错误
            form.querySelectorAll('.input-error').forEach(function(input) { input.classList.remove('input-error'); });
            form.querySelectorAll('.error-message').forEach(function(el) { el.remove(); });
            
            let isValid = true;
            
            if (!name) {
                showError(form.name, '请输入姓名');
                isValid = false;
            }
            
            // 身份证号简单验证
            if (!idCard || !/^\d{18}$/.test(idCard)) {
                showError(form.idCard, '请输入18位有效身份证号');
                isValid = false;
            }
            
            if (!organization) {
                showError(form.organization, '请输入单位名称');
                isValid = false;
            }
            
            if (!position) {
                showError(form.position, '请输入职务');
                isValid = false;
            }
            
            if (!isValid) return;
            
            // 生成唯一ID
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const newId = `FP-${String(personnel.length + 1).padStart(3, '0')}`;
            
            const person = {
                id: newId,
                name: name,
                idCard: idCard,
                organization: organization,
                position: position,
                status: 'active'
            };

            personnel.push(person);
            localStorage.setItem('forensicsPersonnel', JSON.stringify(personnel));
            
            // 记录日志
            const log = {
                id: `LOG-${Date.now()}`,
                time: new Date().toLocaleString('zh-CN'),
                type: '人员添加',
                operator: '当前用户',
                keyId: '-',
                result: 'success',
                details: `成功添加取证人员: ${name}`
            };
            
            const logs = JSON.parse(localStorage.getItem('forensicsLogs')) || [];
            logs.unshift(log);
            localStorage.setItem('forensicsLogs', JSON.stringify(logs));

            closeAddPersonnelModal();
            loadForensicsPersonnel();
            showToast('人员添加成功！', 'success');
        });
        
        // 显示表单错误
        function showError(input, message) {
            input.classList.add('input-error');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            input.parentNode.appendChild(errorDiv);
        }

        // 编辑取证人员
        function editPersonnel(personId) {
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const person = personnel.find(function(p) { return p.id === personId; });
            
            if (!person) return;
            
            const form = document.getElementById('editPersonnelForm');
            form.id.value = person.id;
            form.name.value = person.name;
            form.idCard.value = person.idCard;
            form.organization.value = person.organization;
            form.position.value = person.position;
            form.status.value = person.status;
            
            document.getElementById('editPersonnelModal').classList.remove('hidden');
        }
        
        // 关闭编辑人员模态框
        function closeEditPersonnelModal() {
            document.getElementById('editPersonnelModal').classList.add('hidden');
            const form = document.getElementById('editPersonnelForm');
            form.reset();
            // 清除错误提示
            form.querySelectorAll('.input-error').forEach(function(input) { input.classList.remove('input-error'); });
            form.querySelectorAll('.error-message').forEach(function(el) { el.remove(); });
        }
        
        // 编辑人员表单提交
        document.getElementById('editPersonnelForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 表单验证
            const form = e.target;
            const id = form.id.value;
            const name = form.name.value.trim();
            const idCard = form.idCard.value.trim();
            const organization = form.organization.value.trim();
            const position = form.position.value.trim();
            const status = form.status.value;
            
            // 清除之前的错误
            form.querySelectorAll('.input-error').forEach(function(input) { input.classList.remove('input-error'); });
            form.querySelectorAll('.error-message').forEach(function(el) { el.remove(); });
            
            let isValid = true;
            
            if (!name) {
                showError(form.name, '请输入姓名');
                isValid = false;
            }
            
            if (!idCard || !/^\d{18}$/.test(idCard)) {
                showError(form.idCard, '请输入18位有效身份证号');
                isValid = false;
            }
            
            if (!organization) {
                showError(form.organization, '请输入单位名称');
                isValid = false;
            }
            
            if (!position) {
                showError(form.position, '请输入职务');
                isValid = false;
            }
            
            if (!isValid) return;
            
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const updatedPersonnel = personnel.map(function(person) {
                if (person.id === id) {
                    return { ...person, name, idCard, organization, position, status };
                }
                return person;
            });
            
            localStorage.setItem('forensicsPersonnel', JSON.stringify(updatedPersonnel));
            
            // 记录日志
            const log = {
                id: `LOG-${Date.now()}`,
                time: new Date().toLocaleString('zh-CN'),
                type: '人员编辑',
                operator: '当前用户',
                keyId: '-',
                result: 'success',
                details: `成功编辑取证人员: ${name}`
            };
            
            const logs = JSON.parse(localStorage.getItem('forensicsLogs')) || [];
            logs.unshift(log);
            localStorage.setItem('forensicsLogs', JSON.stringify(logs));
            
            closeEditPersonnelModal();
            loadForensicsPersonnel();
            showToast('人员编辑成功！', 'success');
        });

        // 切换人员状态
        function togglePersonnelStatus(personId) {
            const personnel = JSON.parse(localStorage.getItem('forensicsPersonnel')) || [];
            const person = personnel.find(function(p) { return p.id === personId; });
            
            if (!person) return;
            
            const newStatus = person.status === 'active' ? 'inactive' : 'active';
            const statusText = newStatus === 'active' ? '可用' : '不可用';
            
            // 确认操作
            if (!confirm(`确定要将人员 ${person.name} 的状态修改为 ${statusText} 吗？`)) {
                return;
            }
            
            const updatedPersonnel = personnel.map(function(p) {
                if (p.id === personId) {
                    return { ...p, status: newStatus };
                }
                return p;
            });
            
            localStorage.setItem('forensicsPersonnel', JSON.stringify(updatedPersonnel));
            
            // 记录日志
            const log = {
                id: `LOG-${Date.now()}`,
                time: new Date().toLocaleString('zh-CN'),
                type: '人员状态变更',
                operator: '当前用户',
                keyId: '-',
                result: 'success',
                details: `成功将取证人员 ${person.name} 的状态修改为 ${statusText}`
            };
            
            const logs = JSON.parse(localStorage.getItem('forensicsLogs')) || [];
            logs.unshift(log);
            localStorage.setItem('forensicsLogs', JSON.stringify(logs));
            
            loadForensicsPersonnel();
            showToast(`人员状态已修改为 ${statusText}！`, 'info');
        }

        // 切换验证人员选择
        function toggleVerifierSelection(personId) {
            const checkbox = document.getElementById(`verifier-${personId}`);
            checkbox.checked = !checkbox.checked;
        }

        // 开始MOFN验证
        function startMofnVerification() {
            const keyId = document.getElementById('keyToVerify').value;
            const requiredM = parseInt(document.getElementById('requiredM').value);
            const selectedVerifiers = Array.from(document.querySelectorAll('#verifiersGrid input[type="checkbox"]:checked'));
            const totalN = parseInt(document.getElementById('totalN').value);
            
            // 验证输入
            if (!keyId) {
                showToast('请选择需要验证的密钥！', 'error');
                return;
            }
            
            if (requiredM < 1) {
                showToast('请设置有效的需要验证人数！', 'error');
                return;
            }
            
            if (requiredM > totalN) {
                showToast(`需要验证人数不能超过总人数${totalN}！`, 'error');
                return;
            }

            if (selectedVerifiers.length < requiredM) {
                showToast(`请至少选择${requiredM}个验证人员！`, 'error');
                return;
            }
            
            // 模拟验证过程
            const verifyBtn = event.target;
            const originalText = verifyBtn.innerHTML;
            verifyBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> 验证中...';
            verifyBtn.classList.add('loading');
            
            // 模拟异步验证过程
            setTimeout(function() {
                // 记录验证日志
                const log = {
                    id: `LOG-${Date.now()}`,
                    time: new Date().toLocaleString('zh-CN'),
                    type: 'MOFN验证',
                    operator: selectedVerifiers.map(function(cb) { return cb.labels[0].textContent; }).join(','),
                    keyId: keyId,
                    result: 'success',
                    details: `成功完成密钥${keyId}的${requiredM}/${selectedVerifiers.length}验证`
                };

                const logs = JSON.parse(localStorage.getItem('forensicsLogs')) || [];
                logs.unshift(log);
                localStorage.setItem('forensicsLogs', JSON.stringify(logs));
                
                // 重置按钮
                verifyBtn.innerHTML = originalText;
                verifyBtn.classList.remove('loading');
                
                showToast('MOFN验证成功！', 'success');
                
                // 重置选择
                document.querySelectorAll('#verifiersGrid input[type="checkbox"]').forEach(function(cb) {
                    cb.checked = false;
                });
                
                // 切换到日志标签页
                switchTab('logs');
            }, 1500);
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initData();
            
            // 延迟加载以展示动画效果
            setTimeout(function() {
                loadForensicsPersonnel();
                loadForensicsLogs();
            }, 300);
        });
        
        // 模态框关闭功能（点击外部或ESC键）
        document.addEventListener('click', function(e) {
            const modals = ['addPersonnelModal', 'editPersonnelModal'];
            modals.forEach(function(modalId) {
                const modal = document.getElementById(modalId);
                if (modal && !modal.classList.contains('hidden') && e.target === modal) {
                    if (modalId === 'addPersonnelModal') {
                        closeAddPersonnelModal();
                    } else if (modalId === 'editPersonnelModal') {
                        closeEditPersonnelModal();
                    }
                }
            });
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeAddPersonnelModal();
                closeEditPersonnelModal();
            }
        });
        
        // 确保requiredM不超过totalN
        document.getElementById('requiredM').addEventListener('input', function(e) {
            const requiredM = parseInt(e.target.value);
            const totalN = parseInt(document.getElementById('totalN').value);
            if (requiredM > totalN && totalN > 0) {
                e.target.value = totalN;
            }
        });
    </script>
</body>
</html>